<template>
  <!-- <div>银行收款</div> -->
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-input
          v-model.trim="form.serialNo"
          placeholder="流水单据"
          clearable
          class="w-50"
        />
        <VSelects
          v-model="form.principalId"
          :dataSourse="optionsDataAll.principalIds"
          placeholder="收款主体"
        />
        <VSelects
          v-model="form.currency"
          :dataSourse="optionsDataAll.currency"
          placeholder="币种"
          valueField="label"
        />
        <VGroup>
          <VSelects
            v-model="form.user.type"
            :dataSourse="othersData.personnel"
            class="w-[100px]"
          />
          <VCascader
            v-model="form.user.value"
            collapse-tags
            style="width: 200px"
          />
        </VGroup>
        <VGroupPlus
          v-model="form.time"
          type="createAuditTime"
          rightLabel="time"
        >
        </VGroupPlus>
      </template>
      <template #toolbar_btns>
        <!-- <div class="w-full">
          <el-tabs
            v-if="tabList.length"
            v-model="activeName"
            @tab-click="handleClick"
          >
            <el-tab-pane
              :label="item.status_text"
              :name="item.status"
              v-for="(item, index) in tabList"
              :key="index"
            >
              <template #label>
                {{ item.status_text }}(<span
                  :class="
                    activeName == item.status
                      ? 'base-text-color'
                      : 'text-[#999999]'
                  "
                  >{{ item.count }}</span
                >)
              </template>
            </el-tab-pane>
          </el-tabs>
        </div> -->
        <VActionBar :actions="actions">
          <template #right>
            <div class="ml-auto">
              <VTotal
                ref="totalRef"
                :options="[{ title: '合计收款金额', key: 'wait_payment' }]"
                :child="[{ title: '单量', key: 'num' }]"
              />
            </div>
          </template>
        </VActionBar>
      </template>
    </VTable>
    <VAudit
      v-model="auditVisible"
      title="审核"
      :ids="idAudit"
      url="/receipt/review"
      :isRemark="false"
      :option="[
        { label: '已审核', value: 2 },
        { label: '审核失败', value: 3 },
      ]"
      method="PATCH"
      @close="auditId = null"
      @refresh="refresh"
    />
    <Add
      v-model="addVisible"
      :title="addTitle"
      :data="addData"
      :optionsData="optionsDataAll"
      @refresh="refresh"
      @close="addData = null"
    />
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
    <VLog
      v-model="logVisible"
      :autoLoad="false"
      :module="5"
      :id="logId"
      @close="logId = ''"
    />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { getTableSelectRow } from "@/hooks/tools.js";
import { config_name } from "@/config/export.js";
import tagStatus from "@/components/tagStatus/index.vue";
import othersData from "@/data/search.js";
import VTotal from "@/components/VTotal";
import Add from "./add/index.vue";
import { getReceivablesList, unAuditReceivables } from "./api.js";
import {
  getAccountPrincipal,
  getCurrency,
  getOption,
  getChannelList,
} from "@/api/index.js";
import { capitalAuthList } from "@/Auth/capital.js";
const { proxy } = getCurrentInstance();
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      time: {
        type: "createdAt",
        value: null,
      },
      principalId: "",
      currency: "",
      user: {
        type: "createUser",
        value: "",
      },
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    {
      type: "checkbox",
      width: 50,
      fixed: "left",
    },
    {
      title: "ID",
      field: "id",
      width: 180,
      slots: {
        default: ({ row }) => {
          return <span>{row?.id?.toString() || "-"}</span>;
        },
      },
      fixed: "left",
    },
    {
      title: "流水单据",
      field: "serialNo",
      width: 135,
      fixed: "left",
    },
    {
      title: "状态",
      slots: {
        default: ({ row }) => {
          return (
            <tagStatus
              code={row?.state}
              type={[
                { label: 1, value: "warning" },
                { label: 2, value: "primary" },
                { label: 3, value: "danger" },
              ]}
            />
          );
        },
      },
      width: 90,
    },
    {
      title: "类型",
      slots: {
        default: ({ row }) => {
          return <span>{row.accountType.label}</span>;
        },
      },
      width: 80,
    },
    {
      title: "银行名称",
      field: "accountChannelName",
      minWidth: 100,
    },
    {
      title: "账号/卡号",
      field: "account",
      width: 150,
    },
    {
      title: "收款主体",
      field: "accountPrincipal",
      width: 100,
    },
    {
      title: "收款金额",
      field: "amount",
      width: 120,
    },
    {
      title: "币种",
      field: "currency",
      width: 60,
    },
    {
      title: "汇率",
      field: "exchangeRate",
      width: 100,
    },
    {
      title: "人民币收款金额",
      field: "localAmount",
      width: 120,
    },
    {
      title: "收款说明",
      field: "illustrate",
      width: 200,
    },
    {
      title: "备注",
      field: "remark",
      width: 200,
    },
    {
      title: "收款时间",
      field: "receiptAt",
      width: 170,
    },
    {
      title: "创建人员",
      field: "createUser",
      width: 170,
    },
    {
      title: "添加时间",
      field: "createdAt",
      width: 170,
    },
    {
      title: "审核人员",
      field: "reviewUser",
      width: 170,
    },
    {
      title: "审核时间",
      field: "reviewAt",
      width: 170,
    },
    {
      title: "操作",
      width: 160,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.state.value != 2 && [
                  capitalAuthList.recharge.bank_recharge.edit,
                ] && (
                  <el-button type="primary" link onClick={() => handleAdd(row)}>
                    编辑
                  </el-button>
                )}
              {[capitalAuthList.recharge.bank_recharge.audit] && (
                <el-button
                  type="primary"
                  link
                  onClick={() => handleAuditRow(row)}
                >
                  审核
                </el-button>
              )}
              {[capitalAuthList.recharge.bank_recharge.log] && (
                <el-button
                  type="primary"
                  link
                  onClick={() => handleLog(row.id)}
                >
                  日志
                </el-button>
              )}
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        return getReceivablesList({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
const optionsData = ref({});
const getAccountList = async () => {
  const { data } = await getAccountPrincipal();
  optionsData.value.principalIds = data || [];
};
const currency = async () => {
  const { data } = await getCurrency();
  optionsData.value.currency = data || [];
};
currency();
getAccountList();
const optionsData1 = ref({});
const getOpt = async () => {
  const { data } = await getOption({
    enums: "account_type",
  });
  optionsData1.value = data || {};
};
getOpt();
const getChannel = async () => {
  const { data } = await getChannelList({
    pageNum: 1,
    pageSize: 100,
  });
  optionsData.value.channelList = data || [];
};
const optionsDataAll = computed(() => {
  return {
    ...optionsData.value,
    ...optionsData1.value,
  };
});
getChannel();
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
//新增/编辑
const addVisible = ref(false);
const addData = ref(null);
const addTitle = ref("新增");
const handleAdd = (row) => {
  addVisible.value = true;
  let data = null;
  if (row?.id) {
    data = {
      ...row,
      accountType: row?.accountType?.value,
      accountChannelId: row?.accountChannelId?.toString(),
      accountId: row?.accountId?.toString(),
    };
  }
  addData.value = data || null;
  addTitle.value = data?.id ? "编辑" : "新增";
};
//审核
const auditVisible = ref(false);
const handleAuditRow = (row) => {
  auditVisible.value = true;
  idAudit.value = [row?.id.toString()];
};
const idAudit = ref([]);
const handleAudit = () => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id.toString());
  auditVisible.value = true;
  idAudit.value = ids;
};
const handleUnAudit = () => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id.toString());
  proxy?.confirm({
    title: "反审核",
    content: (
      <p>
        确认选中的
        <span class="text-[#3366F1] px-[4px]">1</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await unAuditReceivables({ ids });
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const handleImport = () => {
  ElMessage.warning("导入");
};
//导出中心
const DerivedCenterRef = ref();
const handleExport = async () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["capital"]["receipt_bank"],
    condition,
  });
};

const logVisible = ref(false);
const logId = ref("");
const handleLog = (item) => {
  logId.value = item;
  logVisible.value = true;
};
const actions = [
  {
    label: "新增",
    type: "primary",
    icon: "add1",
    fn: () => handleAdd(null),
    permission: [capitalAuthList.recharge.bank_recharge.add],
  },
  {
    label: "审核",
    type: "primary",
    fn: () => handleAudit(null),
    permission: [capitalAuthList.recharge.bank_recharge.audit],
  },
  {
    label: "反审核",
    fn: () => handleUnAudit(null),
    permission: [capitalAuthList.recharge.bank_recharge.un_audit],
  },
  {
    label: "导入",
    right: true,
    dkicon: "icon-Download",
    fn: () => handleImport(),
    permission: [capitalAuthList.recharge.bank_recharge.import],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: () => handleExport(),
    permission: [capitalAuthList.recharge.bank_recharge.export],
  },
];
</script>
<style scoped lang="scss">
  :deep(.el-tag.el-tag--danger){
    background-color: var(--base-danger-bg)
  }
  :deep(.el-tag.el-tag--primary){
    background-color: var(--base-primary-bg);
    border-color: var(--base-primary-bg);;
  }
  :deep(.el-tag.el-tag--warning){
    background-color: var(--base-warning-bg);
    border-color: var(--base-warning-bg);;
  }
</style>
